/**
 * @description: TODO
 * @author: candy.d.chen
 * @LastEditors: candy.d.chen
 * @LastEditTime: 2021/11/1 18:08
 */
import axios from 'axios'
// 创建axios实例
// headers: {'Content-type': 'application/x-www-form-urlencoded'}

axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded;charset=UTF-8'
// request拦截器
// axios.interceptors.request.use(
//   config => {
//     config.headers['Content-Type'] = 'application/x-www-form-urlencoded' // 关键所在
//     return config
//   },
//   error => {
//     console.log(error) // for debug
//     Promise.reject(error)
//   }
// )

// response 拦截器
axios.interceptors.response.use(
  response => {
    const res = response.data
    if (res.resultCode !== '000') { // 后台返回码，根据自己的业务进行修改
      Notification.error({
        title: '错误',
        message: res.resultDesc, // 错误描述信息
        duration: 0
      })
      return Promise.reject('error')
    } else {
      return response.data
    }
  },
  error => {
    console.log('err' + error) // for debug
    return Promise.reject(error)
  }
)

function getServiceUrl(url) {
  if (url.startsWith("http") || url.startsWith("https")) {
    return url
  }
  if (process.env.NODE_ENV === "development") {
    return url
  }
  return url
}

export function get(url, notNeedFullLoading) {
  if (!url) {
    return Promise.reject('url is undefined');
  }
  let t = new Date().getTime()
  if (url.indexOf('?') >= 0) {
    url += `&t=/${t}`
  } else {
    url += `?t=/${t}`
  }
  if (notNeedFullLoading === true) {
    return axios.get(getServiceUrl(url))
  } else {
    return axios.get(getServiceUrl(url), {needFullScreenLoading: true})
  }
}

export function post(url, data, notNeedFullLoading) {
  let axiosOpts = {
    method: 'post',
    url: getServiceUrl(url),
    params: {},
    data
  }
  if (url === '/api/auth/login/') axiosOpts['ignoreMsg'] = true
  if (notNeedFullLoading === true) {
    return axios(axiosOpts)
  } else {
    axiosOpts['needFullScreenLoading'] = true
    return axios(axiosOpts)
  }
}


export const getWithCredentials = (url, notNeedFullLoading) => {
  return get(url, notNeedFullLoading, { withCredentials: true })
}

export const postWithCredentials = (url, data, notNeedFullLoading) => {
  return post(url, data, notNeedFullLoading, { withCredentials: true })
}


export default {
  get,
  post,
  getWithCredentials,
  postWithCredentials
}
